from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from user.models import Topic


class TopicRecommender:
    def __init__(self):
        # 获取所有话题
        self.topics = Topic.objects.all()
        # 数据预处理和表示话题
        self.topic_texts = [topic.title + " " + topic.content for topic in self.topics]
        self.vectorizer = CountVectorizer()
        self.topic_matrix = self.vectorizer.fit_transform(self.topic_texts)
    def recommend_topics_for_user(self, user_topic):
        # 计算用户浏览的话题与其他话题之间的相似度
        user_topic_text = user_topic.title + " " + user_topic.content
        user_topic_vector = self.vectorizer.transform([user_topic_text])
        similarities = cosine_similarity(user_topic_vector, self.topic_matrix)
        # 获取相似度最高的几个话题的索引
        similar_topics_indices = similarities.argsort()[0][-5:].astype(int).tolist()  # 假设推荐5个话题
        # 获取相似话题的 id 和标题
        similar_topics = [self.topics[i] for i in similar_topics_indices]
        return similar_topics





